package hn.sigit.logic.security;

import hn.sigit.logic.bpm.ActorType;
import hn.sigit.model.hnd.administrative.HND_UserRoleType;
import hn.sigit.model.hnd.administrative.HND_User;
import hn.sigit.model.hnd.administrative.HND_UserRole;
import hn.sigit.model.hnd.administrative.dao.HND_UserDAO;

import java.util.Iterator;
import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.bpm.Actor;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Stateless
@Name("authenticator")
public class Authenticator implements IAuthenticator
{
    @Logger private Log log;

    @In Identity identity;
    @In Credentials credentials;
    @In(create = true) private Actor actor;
    
    @Out(scope=ScopeType.SESSION, required=false)
    private String loggedUserName;
    
    
    public boolean authenticate() {
        log.info("authenticating {0}", credentials.getUsername());

        String userName = credentials.getUsername();
        String password = credentials.getPassword();
        
        HND_User user = HND_UserDAO.loadUser(userName, password);
        
        if (user != null) {
        	//TODO: arreglar lo del username
        	loggedUserName = "";//user.getParty().getLastName1() + " " + user.getParty().getLastName2() + ", " + user.getParty().getFirstName1() + " " + user.getParty().getFirstName2();
        	actor.setId(userName);
        	
        	for (HND_UserRole role : user.getRoles()) {
            	identity.addRole(role.getRole().toString());
            	
        		if (role.getRole() == HND_UserRoleType.RECEPTIONIST) {
        			actor.getGroupActorIds().add(ActorType.RECEPTIONIST.toString());
        		}
        		else if (role.getRole() == HND_UserRoleType.ANALYST) {
        			actor.getGroupActorIds().add(ActorType.ANALYST.toString());
        			actor.getGroupActorIds().add(ActorType.ANALYST_OR_APPROVER.toString());
        		}
        		else if (role.getRole() == HND_UserRoleType.EDITOR) {
        			actor.getGroupActorIds().add(ActorType.EDITOR.toString());
        		}
        		else if (role.getRole() == HND_UserRoleType.APPROVER) {
        			actor.getGroupActorIds().add(ActorType.APPROVER.toString());
        			actor.getGroupActorIds().add(ActorType.ANALYST_OR_APPROVER.toString());
        		}
        	}
        	return true;
        }

        return false;
    }

	@Override
	public boolean checkIfLoogedIn() {
		return identity.isLoggedIn();
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
}
